package housekeeping.service.Impl;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import housekeeping.mapper.ClientMapper;
import housekeeping.mapper.UserAccountsMapper;
import housekeeping.mapper.UserRegisterMapper;
import housekeeping.mapper.WorkerMapper;
import housekeeping.pojo.Client;
import housekeeping.pojo.UserAccounts;
import housekeeping.pojo.Worker;
import housekeeping.service.UserRegisterService;
import housekeeping.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @version 1.0
 * @Author Du
 * @Date 2025/7/7 16:30
 * @注释 用户注册业务实现类
 */
@Service
public class UserRegisterServiceImpl implements UserRegisterService {

    @Autowired
    private UserRegisterMapper userRegisterMapper;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private WorkerMapper workerMapper;

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不存在", e);
        }
    }
    @Override
    public ServerResult<?> register(UserAccounts user) {
        String phone = user.getAccount();
        String password = user.getPassword();
        String role = user.getRole();

        if (password == null || password.length() < 6 || password.length() > 20) {
            return ServerResult.error(300,"密码长度必须为6-20个字符");
        }

        QueryWrapper<UserAccounts> wrapper = new QueryWrapper<>();
        wrapper.eq("account", phone);
        if (userRegisterMapper.selectOne(wrapper) != null) {
            return ServerResult.error(400,"注册失败，账号已存在");
        }

        String encryptedPassword = md5(password);

        userRegisterMapper.insertPartial(phone,encryptedPassword,role);

        if(user.getRole().equals("worker")){
            userRegisterMapper.insertworker(phone);
        } else if (user.getRole().equals("client")) {
            userRegisterMapper.insertclient(phone);
        }
        return ServerResult.ok(user);
    }
}
